package com.prd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.prd.dto.AttendanceOutsideDTO;
import com.prd.model.AttendanceOutsideDO;
import com.prd.mapper.AttendanceOutsideMapper;
import com.prd.service.AttendanceOutsideService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.prd.util.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.ProcessEngineConfiguration;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.image.ProcessDiagramGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 外勤管理表 服务实现类
 * </p>
 *
 * @author lizhaoyi
 * @since 2023-10-18
 */
@Service
@Slf4j
public class AttendanceOutsideServiceImpl extends ServiceImpl<AttendanceOutsideMapper, AttendanceOutsideDO> implements AttendanceOutsideService {

    @Autowired
    private AttendanceOutsideMapper attendanceOutsideMapper;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private RepositoryService repositoryService;

    @Qualifier("processEngine")
    @Autowired
    private ProcessEngine processEngine;

    /**
     * 申请外勤并启动工作流
     *
     * @param attendanceOutsideDTO
     * @return
     */
    @Override
    public JsonData askForOutside(AttendanceOutsideDTO attendanceOutsideDTO) {
        //启动工作流
        String processInstanceId = startProcess(attendanceOutsideDTO);
        //save
        AttendanceOutsideDO attendanceOutsideDO = dto2Do(attendanceOutsideDTO);
        attendanceOutsideDO.setProcessId(processInstanceId);
        attendanceOutsideDO.setCreatTime(LocalDateTime.now());
        attendanceOutsideMapper.insert(attendanceOutsideDO);

        return JsonData.buildSuccess();
    }


    /**
     * 分页查询外勤记录
     * @param page
     * @param size
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> page(int page, int size,String userId) {
        Page<AttendanceOutsideDO> pageInfo = new Page<>(page, size);

        IPage<AttendanceOutsideDO> productDOIPage = attendanceOutsideMapper.selectPage(pageInfo, new QueryWrapper<AttendanceOutsideDO>().eq("user_id",userId));

        Map<String, Object> pageMap = new HashMap<>(3);

        pageMap.put("total_record", productDOIPage.getTotal());
        pageMap.put("total_page", productDOIPage.getPages());
        pageMap.put("current_data", productDOIPage.getRecords().stream().map(obj -> do2Dto(obj)).collect(Collectors.toList()));

        return pageMap;
    }

    /**
     * 查看工作流程图
     *
     * @param resp
     * @param processId
     */
    @Override
    public void showProcessPic(HttpServletResponse resp, String processId) throws IOException {
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if (pi == null) {
            return;
        }
        List<Execution> executions = runtimeService
                .createExecutionQuery()
                .processInstanceId(processId)
                .list();

        List<String> activityIds = new ArrayList<>();
        List<String> flows = new ArrayList<>();
        for (Execution exe : executions) {
            List<String> ids = runtimeService.getActiveActivityIds(exe.getId());
            activityIds.addAll(ids);
        }

        /**
         * 生成流程图
         */
        BpmnModel bpmnModel = repositoryService.getBpmnModel(pi.getProcessDefinitionId());
        ProcessEngineConfiguration engconf = processEngine.getProcessEngineConfiguration();
        ProcessDiagramGenerator diagramGenerator = engconf.getProcessDiagramGenerator();
        InputStream in = diagramGenerator.generateDiagram(bpmnModel, "png", activityIds, flows, engconf.getActivityFontName(), engconf.getLabelFontName(), engconf.getAnnotationFontName(), engconf.getClassLoader(), 1.0, false);
        OutputStream out = null;
        byte[] buf = new byte[1024];
        int legth = 0;
        try {
            out = resp.getOutputStream();
            while ((legth = in.read(buf)) != -1) {
                out.write(buf, 0, legth);
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }

    }

    /**
     * 查询外勤详情
     * @param id
     * @param userId
     * @return
     */
    @Override
    public JsonData getDetail(int id, String userId) {

        QueryWrapper<AttendanceOutsideDO> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        wrapper.eq("user_id",userId);
        AttendanceOutsideDO attendanceOutsideDO = attendanceOutsideMapper.selectOne(wrapper);

        return JsonData.buildSuccess(attendanceOutsideDO);
    }

    private String startProcess(AttendanceOutsideDTO attendanceOutsideDTO) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("zuzhangTask", attendanceOutsideDTO.getApprove());
        // 开启流程的key，就是流程定义文件里 process 标签的id
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("ask_for_outside", map);
        // 设置一些参数
        runtimeService.setVariable(processInstance.getId(), "name", attendanceOutsideDTO.getAskOutsideName());
        runtimeService.setVariable(processInstance.getId(), "reason", attendanceOutsideDTO.getTitle());
        runtimeService.setVariable(processInstance.getId(), "date", attendanceOutsideDTO.getOutsideDate());
        log.info("创建外勤流程 processId：{}", processInstance.getId());
        return processInstance.getId();
    }

    private AttendanceOutsideDO dto2Do(AttendanceOutsideDTO attendanceOutsideDTO) {
        AttendanceOutsideDO attendanceOutsideDO = new AttendanceOutsideDO();
        BeanUtils.copyProperties(attendanceOutsideDTO, attendanceOutsideDO);
        return attendanceOutsideDO;
    }

    private AttendanceOutsideDTO do2Dto(AttendanceOutsideDO attendanceOutsideDO) {
        AttendanceOutsideDTO attendanceOutsideDTO = new AttendanceOutsideDTO();
        BeanUtils.copyProperties(attendanceOutsideDO, attendanceOutsideDTO);
        return attendanceOutsideDTO;
    }
}
